package hutech.ksv.dao;

import hutech.ksv.entity.ChiTietPNXQAEntity;
import hutech.ksv.entity.PhieuNhanXetQAEntity;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class PhieuNhanXetQADao implements Serializable {

	@Autowired
	DataSource dataSource;

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// Test connection
	public Connection getConnection() {
		try {
			Class.forName("com.mysql.jdbc.Driver");
			return DriverManager.getConnection(
					"jdbc:mysql://localhost:3306/mydb", "root", "mysql@123");
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	// Load phieu nhan xet quan an
	public List<PhieuNhanXetQAEntity> loadNhanXetQA() {
		String query = "SELECT * FROM `PhieuNhanXetQA`";
		List<PhieuNhanXetQAEntity> listPhieuNhanXetQA = new ArrayList<PhieuNhanXetQAEntity>();

		Connection conn = null;
		PreparedStatement preparedStatement = null;

		try {
			conn = dataSource.getConnection();
			preparedStatement = conn.prepareStatement(query);
			ResultSet rs = preparedStatement.executeQuery();
			while (rs.next()) {
				listPhieuNhanXetQA.add(new PhieuNhanXetQAEntity(rs.getInt(1),
						rs.getInt(2), rs.getString(3)));
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (preparedStatement != null) {
					preparedStatement.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return listPhieuNhanXetQA;
	}

	// Load chi tiet phieu nhan xet quan an
	public List<ChiTietPNXQAEntity> loadCTNhanXetQA() {
		String query = "SELECT * FROM `ChiTietPNXQA`";
		List<ChiTietPNXQAEntity> listCTPhieuNhanXetQA = new ArrayList<ChiTietPNXQAEntity>();

		Connection conn = null;
		PreparedStatement preparedStatement = null;

		try {
			conn = dataSource.getConnection();
			preparedStatement = conn.prepareStatement(query);
			ResultSet rs = preparedStatement.executeQuery();
			while (rs.next()) {
				listCTPhieuNhanXetQA.add(new ChiTietPNXQAEntity(rs.getInt(1),
						rs.getInt(2), rs.getString(3)));
			}
			rs.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (preparedStatement != null) {
					preparedStatement.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return listCTPhieuNhanXetQA;
	}
}
